import Taro, { useLoad, useReachBottom, useRouter } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { useEffect, useState } from 'react'
import { getAllCategory, getHomeProductList } from '@/api/myOrder'
import { ProductList } from '@/components/ProductList'
import styles from './index.module.scss'

export interface Datum {
  channelLogo: string
  channelName: string
  description: null
  id: number
  ordered: null
  status: null
  [property: string]: any
}

export default function Category() {
  const router = useRouter()
  const [categoryList, setCategoryList] = useState<Datum[]>([])
  const [current, setCurrent] = useState(0)
  const [categoryData, setCategoryData] = useState<{
    [categoryId: number]: any[]
  }>({})
  const [reqData, setReqData] = useState({
    page: 1,
    pageSize: 5,
    channelId: Number(router.params.id),
  })
  const [isMoreData, setIsMoreData] = useState(true)

  const fetchGetAllCategory = async () => {
    const res = await getAllCategory()
    if (res.code == 0) {
      setCategoryList(res.data)
      setCurrent(res.data.findIndex((item) => item.id == router.params.index))
    } else {
      Taro.showToast({
        title: res.msg,
        icon: 'none',
      })
    }

    const index = res.data.findIndex(
      (item) => item.id == Number(router.params.id),
    )
    setCurrent(index)
  }

  useLoad(() => {
    fetchGetAllCategory()
  })

  /** 点击一个Tab栏时，高亮当前Tab, 判断是不是已经拥有该分类的数据 */
  const handleClick = async (value) => {
    setCurrent(value)
    setIsMoreData(true)
    const categoryId = categoryList[value].id

    if (!categoryData[categoryId]) {
      setReqData({
        ...reqData,
        channelId: categoryId,
      })
    }
  }

  const fetchCategoryData = async () => {
    const res = await getHomeProductList(reqData)

    if (res && res.code === 0) {
      setCategoryData({
        ...categoryData,
        [reqData.channelId]: categoryData[reqData.channelId]
          ? [...categoryData[reqData.channelId], ...res.data]
          : res.data,
      })
    } else if (res.code === 1002) {
      Taro.showToast({
        title: '没有更多数据了',
        icon: 'none',
      })
      setIsMoreData(false)
    } else {
      Taro.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  }

  useEffect(() => {
    fetchCategoryData()
  }, [reqData])

  useReachBottom(() => {
    if (isMoreData) {
      setReqData((pre) => ({
        ...reqData,
        page: pre.page + 1,
      }))
    }
  })

  return (
    <div className={styles.category}>
      <AtTabs
        current={current}
        scroll
        tabList={categoryList.map((item) => ({
          title: item.channelName,
        }))}
        onClick={(index) => handleClick(index)}
      >
        {categoryList.map((item, index) => (
          <AtTabsPane key={item.id} current={current} index={index}>
            <div className={styles.tabContent}>
              {categoryData[item.id] && categoryData[item.id].length > 0 ? (
                <ProductList list={categoryData[item.id]}></ProductList>
              ) : (
                <p>No data</p>
              )}
            </div>
          </AtTabsPane>
        ))}
      </AtTabs>
    </div>
  )
}
